<template>
  <form class="tw-liblogin"
    @keydown.enter="login">
    <div class="tw-liblogin-inputbox xusername">
      <input class="tw-liblogin-input"
        v-model="username"
        @blur="checkRepeat"
        :placeholder="usernamePlaceholder"
        type="index" />
    </div>

    <div class="tw-liblogin-inputbox xpassword">
      <input class="tw-liblogin-input"
        v-model="password"
        :placeholder="passwordPlaceholder"
        type="password" />
    </div>

    <template v-if="useOrgList">
      <!-- <div class="tw-liblogin-selectbox" v-show="chooseOrg">
    <select required
      class="tw-liblogin-select"
      v-model="userId"
      filterable
      placeholder="请选择机构">
      <option value=null disabled selected hidden style='display:none;'>请选择机构</option>
      <option v-for="org in orgList"
        :key="org.userId"
        :label="org.orgUserName"
        :value="org.userId">
      </option>
    </select>
    <i class="xarrow-down el-icon-hahaha" ></i>
  </div> -->
      <el-select v-show="chooseOrg"
        class="tw-liblogin-eselectbox"
        v-model="userId"
        filterable
        :placeholder="'请选择机构'">
        <el-option v-for="org in orgList"
          :key="org.userId"
          :label="org.orgUserName"
          :value="org.userId">
        </el-option>
      </el-select>
    </template>

    <!-- 以下代码因接口还没好，先注释掉，等接口好了再放开 -->
    <template v-if="isCaptcha">
      <div v-show="showCaptcha">
        <div class="tw-liblogin-inputbox xcaptche"
          v-if="captchaType==='code'">
          <input class="tw-liblogin-input"
            v-model="captcha"
            :placeholder="'请输入验证码'"
            type="index" />
          <a :class="['tw-liblogin-code', {'disable-click': disabled}]"
            @click="getCaptcha">{{tipText}}</a>
        </div>
        <!-- clickWord -->
        <div class="tw-liblogin-inputbox xpoint"
          v-else-if="captchaType==='click'">
          <Verify @success="handleSuccess"
            @error="handleError"
            :captchaType="captchaType"
            :captchaColor="{ sucColor: sucColor, errColor: errColor, movColor: movColor}"
            :imgSize="{ width: imgWidth, height: imgHeight, verifyFloat: verifyFloat }"></Verify>
        </div>
        <!-- blockPuzzle -->
        <div class="tw-liblogin-inputbox xpoint"
          v-else-if="captchaType==='slide'">
          <Verify @success="handleSuccess"
            @error="handleError"
            :captchaType="captchaType"
            :captchaColor="{ sucColor: sucColor, errColor: errColor, movColor: movColor}"
            :imgSize="{ width: imgWidth, height: imgHeight, verifyFloat: verifyFloat }"></Verify>
        </div>
      </div>
    </template>

    <div class="tw-liblogin-text xright">
      <div class="tw-liblogin-text-left">
        <i :class="{twtips: errMsg}"></i>
        <span class="tw-liblogin-error">{{errMsg}}</span>
      </div>

      <div class="tw-liblogin-text-right">
        <!-- <a class="tw-liblogin-findpwd" :href="findPwdUrl">忘记密码</a> -->
      </div>
    </div>

    <a class="tw-liblogin-btn"
      @click="login">登录</a>

    <div class="tw-liblogin-text">
      <div class="tw-liblogin-text-center"
        v-if="!isConcise">
        <a :style="{fontWeight: linkWeight ? '700':'400'}"
          class="tw-liblogin-findpwd"
          :href="findPwdUrl">忘记密码</a>
        <span class="xcut"> | </span>
        <a :style="{fontWeight: linkWeight ? '700':'400'}"
          class="tw-liblogin-findpwd"
          :href="registerUrl">立即注册</a>
      </div>
      <div class="tw-liblogin-text-center"
        v-else>
        <a :href="toHome">{{linkText}}</a>
      </div>
    </div>

    <div class="tw-liblogin-other"
      v-if="useThirdLogin">
      <div class="tw-liblogin-other-text">
        {{thirdLabel|'其他方式登录：'}}
      </div>
      <div class="tw-liblogin-other-img"
        v-if="thirdlinks.length > 0">
        <a :href="thirdlinks[0].href"
          class="xlink"
          v-if="thirdlinks[0]"
          target="_blank">
          <div class="xborder">
            <img v-if="thirdIcon[0] && thirdIcon[0].localPath"
              class="ximg"
              :src="`${$twApp.fileBaseUrl}${thirdIcon[0].localPath}`" />
            <img v-else
              class="ximg"
              src="@assets/WeChat.png">
          </div>
        </a>
        <a :href="thirdlinks[1].href"
          class="xlink"
          v-if="thirdlinks[1]"
          target="_blank">
          <div class="xborder">
            <img v-if="thirdIcon[1] && thirdIcon[1].localPath"
              class="ximg"
              :src="`${$twApp.fileBaseUrl}${thirdIcon[1].localPath}`" />
            <img v-else
              class="ximg"
              src="@assets/QQ.png">
          </div>
        </a>
        <!-- <a href="" style="margin-right:10px;">
      <div style="display:inline-block;width:24px;height:24px;line-height:20px;text-align:center;border:1px solid #ccc; border-radius:12px;">
        <img style="height:15px" src="@assets/GitHub.png">
      </div>
      </a> -->
      </div>
    </div>
  </form>
</template>

<script>
import props from './props'
import style from '../tw-lib-base/style'
import Verify from './Verify'

export default {
  name: 'tw-liblogin',

  props,

  components: { Verify },

  mixins: [style],

  data() {
    return {
      username: '',
      password: '',
      errMsg: '',
      captcha: '',
      showCaptcha: false,
      chooseOrg: false,
      userId: null,
      orgList: [],

      tipText: '获取验证码',
      time: 60,
      disabled: false
    }
  },

  created() {
    if (this.isCaptcha) {
      let showCaptcha = this.$ui.cookie.get('showCaptcha')
      if (showCaptcha && showCaptcha === '1') {
        this.showCaptcha = true
      }
    }
  },

  computed: {
    style() {
      return {
        linkColor: this.linkColor,
        isConcise: this.isConcise,
        linkText: this.linkText,
        toHome: this.toHome,
        btnColor: this.btnColor,
        thirdSize: this.thirdSize
      }
    }
  },

  methods: {
    setStyle() {
      let style = `
        ::root .tw-liblogin-text a,
        ::root .tw-liblogin-text .xcut {
          color: ${this.linkColor};
        }

        ::root .tw-libcaptcha-verify .verify-bar-area .verify-move-block:hover {
          background-color: ${this.movColor};
        }

        ::root .tw-liblogin-btn {
          background-color: ${this.btnColor};
        }

        ::root tw-liblogin-text-center {
          color: red;
        }

        .tw-liblogin-input, .tw-liblogin-select {
          height: ${this.lineHeight};
          line-height: ${this.lineHeight};
          border-radius: ${this.lineBorder};
        }
        .tw-liblogin-btn {
          border-radius: ${this.lineBorder};
        }
        .tw-liblogin-inputbox,
        .tw-liblogin-eselectbox,
        .tw-liblogin-selectbox,
        .tw-liblogin-btn {
          margin-bottom: ${this.lineBottom};
        }
      `
      if (parseInt(this.lineBottom) < 15) {
        style += `
          .tw-liblogin-text {
            margin-bottom: 10px;
          }
        `
      }

      if (this.useThirdLogin) {
        style += `
          ::root .tw-liblogin-other {
            justify-content: center;
          }
          ::root .tw-liblogin-other-text {
            color: ${this.otherColor};
          }
          ::root .tw-liblogin-other-img .xlink {
            margin-left: ${this.thirdMgLeft};
          }

          ::root .tw-liblogin-other-img .xborder {
            width: ${this.thirdSize};
            height: ${this.thirdSize};
          }
        `
      }

      // !window.$twApp.user.accreditUrl

      // 定制样式
      if (this.customizedStyle && this.customizedStyle === 'shisan') {
        style += `
          ::root .tw-liblogin-other {
            flex-direction: column;
          }
          ::root .tw-liblogin-other-img .xlink {
            margin-left: 0;
          }
          ::root .tw-liblogin-other-img .xlink {
            margin: ${this.thirdMgLeft};
          }
        `
      }

      this.addStyle(style)
    },

    login() {
      const vm = this

      if (this.username === '') {
        this.errMsg = '请输入用户名'
        return
      }

      if (this.password === '') {
        this.errMsg = '请输入密码'
        return
      }
      if (vm.showCaptcha && this.isCaptcha && this.captcha === '') {
        if (this.captchaType === 'code') {
          this.errMsg = '请输入验证码'
        } else {
          this.errMsg = '请完成验证'
        }
        return
      }

      this.errMsg = ''
      const data = {
        type: 'password',
        username: this.username,
        password: this.password,
        loginSuccessUrl: this.loginSuccessUrl
      }
      if (this.isCaptcha && vm.showCaptcha) {
        data.captchaToken = this.captcha
      }
      if (vm.useOrgList && vm.userId) {
        data.uid = vm.userId
        data.version = '01'
      }

      this.$ui
        .login(data)
        .then(() => {
          vm.$ui.cookie.set('showCaptcha', '0')
          let u = localStorage.getItem('$user') || ''
          let user
          if (u) {
            user = JSON.parse(u)
          } else {
            user = window.$twApp.user || {}
          }
          if (!!user && user.userId) {
            vm.$ui.cookie.set('common_access_token', user.token)
            localStorage.setItem('navigation_' + user.userId, JSON.stringify(user))
            localStorage.setItem('navigation_current_user_id', user.userId)
          }
        })
        .catch(err => {
          if (err.response && err.response.data) {
            if (
              [8000, 8001, 8002, 8004, 8007, 8008].includes(
                err.response.data.errorCode
              )
            ) {
              vm.errMsg = err.response.data.errorMesage
            } else if (err.response.data.errorCode === 8005) {
              vm.errMsg = '请选择机构及角色'
              if (vm.useOrgList) {
                let error = err.response.data
                vm.orgList = []
                vm.userId = null
                let userList =
                  error.userList != null
                    ? error.userList
                    : error.exception.userList
                for (let i = 0; i < userList.length; i++) {
                  let u = userList[i]
                  if (u.userId.startsWith('CJTWBS1')) {
                    continue
                  }
                  let orgObject = {}
                  let roleName = ''
                  let orgName = ''
                  let realName = ''
                  if (u.roleName) {
                    roleName = u.roleName
                  }
                  if (u.orgName) {
                    orgName = u.orgName
                  }
                  if (u.realName) {
                    realName = u.realName
                  }

                  orgObject.orgUserName =
                    orgName + '(' + realName + roleName + ')'
                  orgObject.userId = u.userId
                  vm.orgList.push(orgObject)
                  if (i === 0) {
                    vm.userId = u.userId
                    //vm.username = realName
                  }
                }
                if (vm.orgList.length === 1) {
                  vm.userId = vm.orgList[0].userId
                  vm.login()
                  return
                }
                vm.chooseOrg = true
              }
            } else {
              vm.errMsg = '登录异常，请重试'
            }
          } else {
            vm.errMsg = '网络异常，请重试'
          }
          if (vm.isCaptcha) {
            vm.showCaptcha = true
            vm.$ui.cookie.set('showCaptcha', '1')
          }
        })
    },

    // 点击获取验证码
    getCaptcha() {
      if (!this.disabled) {
        this.setDisabled(true)
        this.timer()
      } else {
        return false
      }
    },
    // 倒计时
    timer() {
      if (this.time > 0) {
        this.tipText = this.time + 's后重新获取'
        this.time--
        setTimeout(this.timer, 1000)
      } else {
        this.setDisabled(false)
        this.time = 60
        this.tipText = '重新获取'
      }
    },
    // 设置disable的值
    setDisabled(val) {
      this.disabled = val
    },
    handleSuccess(val) {
      this.errMsg = ''
      this.captcha = val.captchaVerification
    },
    handleError(val) {
      this.captcha = ''
      this.errMsg = '验证失败，请重新验证'
    },
    checkRepeat() {
      let vm = this
      if (vm.useOrgList) {
        if (vm.username && vm.username !== '') {
          window.axios
            .post(window.$twApp.gateway + '/openapi-uc/uc/checkUserRepeat', {
              name: vm.username
            })
            .then(function(response) {
              if (
                response.data.pageInfo &&
                response.data.pageInfo.list &&
                response.data.pageInfo.list.length > 1
              ) {
                vm.orgList = []
                let userList = response.data.pageInfo.list
                for (let i = 0; i < userList.length; i++) {
                  let u = userList[i]
                  let orgObject = {}
                  let roleName = ''
                  let orgName = ''
                  let realName = ''
                  if (u.roleName) {
                    roleName = u.roleName
                  }
                  if (u.orgName) {
                    orgName = u.orgName
                  }
                  if (u.realName) {
                    realName = u.realName
                  }
                  orgObject.orgUserName =
                    orgName + '(' + realName + roleName + ')'
                  orgObject.userId = u.userId
                  vm.orgList.push(orgObject)
                }
                vm.chooseOrg = true
                vm.userId = userList[0].userId
              } else {
                vm.chooseOrg = false
                vm.orgList = []
                vm.userId = null
              }
            })
        } else {
          vm.chooseOrg = false
          vm.orgList = []
          vm.userId = null
        }
      }
    }
  },

  watch: {
    // swiperConfig: {
    //   deep: true,
    //   handler (val, old) {
    //     this.init()
    //   }
    // }
  }
}
</script>

<style lang="scss">
@import './css/index.scss';
</style>
